# -*- coding: utf-8 -*-
import logging
from md5 import md5

from pymylib.lib.base import *
from pymylib.model import Session, User
from pymylib.lib.utils import *

log = logging.getLogger(__name__)

class LoginController(BaseController):
    template_prefix = '/login'
    
    def index(self):
        session['user'] = "anonymous"
        session.save()
        
        #return redirect_to(h.url_for(controller='biblio'))
        redirect_to(action='login')
        
    def login(self):
        """
        Show login form. Submits to /login/submit
        """
        return render(self.template_prefix + '/login.mako')

    def submit(self):
        """
        Verify username and password
        """
        
        # Both fields filled?
        form_username = str(request.params.get('username'))
        form_password = str(request.params.get('password'))

        # Get user data from database
        user_q = Session.query(User)
        db_user = user_q.get_by(user_name=form_username)
	
        if db_user is None: # User does not exist
            return render(self.template_prefix + '/login.mako')

        # Wrong password? (MD5 hashes used here)
	if db_user.password is not None:
            if db_user.password != md5(form_password).hexdigest():
                return render(self.template_prefix + '/login.mako')

        # Mark user as logged in
        session['user_id'] = db_user.id
        session['user'] = form_username
        session['fio'] = db_user.fio
        session['libUser'] = CheckBit(db_user.permitions, 3)
        session['librarianUser'] = CheckBit(db_user.permitions, 2)
        session['editClassificators'] = CheckBit(db_user.permitions, 1)
        session['adminAccess'] = CheckBit(db_user.permitions, 0)
        session.save()

        # Send user back to the page he originally wanted to get to
        if session.get('path_before_login'):
            redirect_to(session['path_before_login'])
        else: # if previous target is unknown just send the user to a welcome page
            return redirect_to(h.url_for(controller='biblio'))

    def logout(self):
        """
        Logout the user and display a confirmation message
        """
        if 'user' in session:
            del session['user']
            del session['user_id']
            del session['fio']            
            del session['libUser']
            del session['librarianUser']
            del session['editClassificators']
            del session['adminAccess']
            del session['sort_name']
            session.save()
        return render(self.template_prefix + '/logout.mako')
